package cn.igroup.server.nio;

import cn.igroup.server.nio.event.SystemShutdown;
import cn.igroup.server.nio.server.NioServer;
import io.netty.channel.ChannelFuture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import sun.misc.Signal;

/**
 * @author long
 * @date 17-1-13
 */
@SpringBootApplication
public class Bootstrap implements CommandLineRunner {

    private static Signal signal = new Signal(getOSSignalType());
    private static SystemShutdown shutdownHandler = new SystemShutdown();

    @Autowired
    public NioServer server;

    public static void main(String[] args) {
        Signal.handle(signal, shutdownHandler);
        new SpringApplicationBuilder(Bootstrap.class)
                .web(false)
                //.listeners(new ApplicationListener())
                .run(args);
    }

    private static String getOSSignalType() {
        return System.getProperties().getProperty("os.name").toLowerCase().startsWith("win") ? "INT" : "USR2";
    }

    @Override
    public void run(String... strings) throws Exception {
        System.out.println("CommandLineRunner ---------------------------------------------");
        ChannelFuture future = server.start();
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                System.out.println("ShutdownHook ---------------------------------------------");
                server.stop();
            }
        });
        future.channel().closeFuture().syncUninterruptibly();
    }
}
